package cn.yours.web.controller;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 2024/6/11 18:39
 * wuhon
 * cn.yours.web.controller
 * file-elfinder
 */
@RestController
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取文件名
            String filename = file.getOriginalFilename();
            // 保存文件到指定路径
            Path path = Paths.get(uploadDir + File.separator + filename);
            Files.write(path, file.getBytes());

            // 返回文件的访问URL
            String fileUrl = "/uploads/" + filename;
            return ResponseEntity.ok().body("{\"location\": \"" + fileUrl + "\"}");
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
